from tortoise import fields
from tortoise.models import Model
from pydantic import BaseModel

from tortoise import Tortoise, run_async, connections
from config import config

import asyncio

MYSQL_HOST = config.MYSQL_HOST
MYSQL_PORT = config.MYSQL_PORT
MYSQL_USER = config.MYSQL_USER
MYSQL_PASSWORD = config.MYSQL_PASSWORD
MYSQL_DATABASE = config.MYSQL_DATABASE


class AccountForSignup(BaseModel):
    username: str
    password: str


class AccountForLogin(AccountForSignup):
    pass


class AccountPublic(BaseModel):
    username: str
    id: int


class Account(Model):
    id = fields.IntField(primary_key=True, unique=True, generated=True)
    username = fields.CharField(max_length=32, null=False, unique=True)
    hashed_password = fields.CharField(max_length=255, null=False)
    role = fields.CharField(max_length=32, null=False, default="[]")
    saved_matrices = fields.CharField(max_length=255, default="[]")
    created_at = fields.DatetimeField(null=False, auto_now_add=True)
    updated_at = fields.DatetimeField(auto_now=True)

    class Meta:
        table_description = "Account table"
        table = "account"


TORTOISE_MODELS = ['__main__']
TORTOISE_CONFIG = {
    'connections': {
        'default': {
            'engine': 'tortoise.backends.mysql',
            'credentials': {
                'host': "127.0.0.1",
                'port': MYSQL_PORT,
                'user': MYSQL_USER,
                'password': MYSQL_PASSWORD,
                'database': MYSQL_DATABASE,
            }
        },
        'LA Connection': {
            'engine': 'tortoise.backends.mysql',
            'credentials': {
                'host': "127.0.0.1",
                'port': MYSQL_PORT,
                'user': MYSQL_USER,
                'password': MYSQL_PASSWORD,
                'database': "la_account",
            }
        }
    },
    'apps': {
        'la_models': {
            'models': TORTOISE_MODELS,
            'default_connection': 'LA Connection'
        }
    },
    'use_tz': False,
    'timezone': 'Asia/Shanghai'
}


async def init() -> None:
    await Tortoise.init(config=TORTOISE_CONFIG)
    await Tortoise.generate_schemas(safe=True)

async def create_account():
    account = await Account.create(username="no1", hashed_password="no1pwd",role="admin")

asyncio.run(init())
